package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.User;
import com.weilai.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "编辑用户信息")
@RequestMapping("/edit-person")
public class UpdateUserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "获取编辑个人信息数据")
    @GetMapping
    public ModelAndView editPage(HttpServletRequest request) {
        try {
            ModelAndView mav = new ModelAndView();
            HttpSession session = request.getSession(false);

            // 检查会话是否存在
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "请先登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 检查用户是否存在
            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户不存在");
            }
            user.setPassword("****");

            mav.addObject("user", user);
            mav.setViewName("editPerson");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "获取用户信息失败", e);
        }
    }

    @ApiOperation(value = "修改性别", notes = "")
    @PostMapping("/updateGender")
    public Map<String, Object> updateGender(@RequestBody String gender, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            HttpSession session = request.getSession(false);

            // 检查会话
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "会话已过期，请重新登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 参数校验
            if (gender == null || gender.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "性别不能为空");
            }

            user.setGender(gender);
            userService.updateUser(user);

            // 构建成功响应
            result.put("success", true);
            result.put("redirectUrl", "/editPerson");
            result.put("message", "性别修改成功");

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "修改性别失败", e);
        }

        return result;
    }


    @ApiOperation(value = "修改用户名", notes = "")
    @PostMapping("/updateUsername")
    public Map<String, Object> updateUsername(@RequestParam String username, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>(); // 统一响应格式

        try {
            // 参数校验
            if (username == null || username.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "用户名不能为空");
            }

            if (username.length() < 2 || username.length() > 8) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR,
                        "用户名长度应在2-8个字符之间");
            }

            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "会话已过期，请重新登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            user.setUsername(username);
            userService.updateUser(user); // 执行更新操作

            // 成功响应
            response.put("success", true);
            response.put("redirectUrl", "/editPerson");
            response.put("message", "用户名修改成功");

        } catch (BusinessException e) { // 业务异常（如参数错误、未登录）
            response.put("success", false);
            response.put("code", e.getErrorCode());
            response.put("message", e.getErrorMessage());
        } catch (Exception e) { // 系统异常（如数据库错误）
            response.put("success", false);
            response.put("code", Code.SYSTEM_UNKNOWN_ERROR);
            response.put("message", "修改用户名失败");
        }

        return response;
    }

    @ApiOperation(value = "修改简介", notes = "")
    @PostMapping("/updateBio")
    public Map<String, Object> updateBio(@RequestParam String bio, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>(); // 统一响应结构

        try {
            // 参数校验：简介长度
            if (bio != null && bio.length() > 500) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR,
                        "简介长度应在500个字符之内");
            }

            // 会话校验
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "会话已过期，请重新登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 执行更新
            user.setBio(bio);
            userService.updateUser(user);

            // 成功响应
            response.put("success", true);
            response.put("redirectUrl", "/editPerson");
            response.put("message", "简介修改成功");

        } catch (BusinessException e) { // 业务异常（参数、权限等）
            response.put("success", false);
            response.put("code", e.getErrorCode());
            response.put("message", e.getErrorMessage());
        } catch (Exception e) { // 系统异常（数据库、未知错误）
            response.put("success", false);
            response.put("code", Code.SYSTEM_UNKNOWN_ERROR);
            response.put("message", "修改简介失败");
        }

        return response;
    }

    @ApiOperation(value = "修改一句话介绍", notes = "")
    @PostMapping("/updateShortBio")
    public Map<String, Object> updateShortBio(@RequestParam String shortBio, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>(); // 统一响应结构

        try {
            // 参数校验：长度限制
            if (shortBio != null && shortBio.length() > 30) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR,
                        "一句话介绍长度应在30个字符之内");
            }

            // 会话校验
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "会话已过期，请重新登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 执行更新
            user.setShortBio(shortBio);
            userService.updateUser(user);

            // 成功响应
            response.put("success", true);
            response.put("redirectUrl", "/editPerson");
            response.put("message", "一句话介绍修改成功");

        } catch (BusinessException e) { // 业务异常（参数、权限等）
            response.put("success", false);
            response.put("code", e.getErrorCode());
            response.put("message", e.getErrorMessage());
        } catch (Exception e) { // 系统异常（数据库、未知错误）
            response.put("success", false);
            response.put("code", Code.SYSTEM_UNKNOWN_ERROR);
            response.put("message", "修改一句话介绍失败");
        }

        return response;
    }

    @ApiOperation(value = "修改居住地", notes = "")
    @PostMapping("/updateLocation")
    public Map<String, Object> updateLocation(@RequestParam String location, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>(); // 统一响应结构

        try {
            // 会话校验
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "会话已过期，请重新登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 执行更新
            user.setLocation(location);
            userService.updateUser(user);

            // 成功响应
            response.put("success", true);
            response.put("redirectUrl", "/editPerson");
            response.put("message", "居住地修改成功");

        } catch (BusinessException e) { // 业务异常（权限等）
            response.put("success", false);
            response.put("code", e.getErrorCode());
            response.put("message", e.getErrorMessage());
        } catch (Exception e) { // 系统异常（数据库、未知错误）
            response.put("success", false);
            response.put("code", Code.SYSTEM_UNKNOWN_ERROR);
            response.put("message", "修改居住地失败");
        }

        return response;
    }

    @ApiOperation(value = "修改行业", notes = "")
    @PostMapping("/updateIndustry")
    public Map<String, Object> updateIndustry(@RequestParam String industry, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>(); // 统一响应结构

        try {
            // 会话校验
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "会话已过期，请重新登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 执行更新
            user.setIndustry(industry);
            userService.updateUser(user);

            // 成功响应
            response.put("success", true);
            response.put("redirectUrl", "/editPerson");
            response.put("message", "行业修改成功");

        } catch (BusinessException e) { // 业务异常（权限等）
            response.put("success", false);
            response.put("code", e.getErrorCode());
            response.put("message", e.getErrorMessage());
        } catch (Exception e) { // 系统异常（数据库、未知错误）
            response.put("success", false);
            response.put("code", Code.SYSTEM_UNKNOWN_ERROR);
            response.put("message", "修改行业失败");
        }

        return response;
    }
}
